//
//  HQYQRCodeScanerViewController.m
//  Go!
//
//  Created by rimi on 16/7/18.
//  Copyright © 2016年 黄秋燕. All rights reserved.
//

#import "HQYQRCodeScanerViewController.h"
#import <AVFoundation/AVFoundation.h>

@interface HQYQRCodeScanerViewController () <AVCaptureMetadataOutputObjectsDelegate>
@property (nonatomic, strong) AVCaptureSession *session; /**< 连接输入/出设备 */
@property (nonatomic, strong) AVCaptureVideoPreviewLayer *previewLayer; /**< 预览图层 */

@end

@implementation HQYQRCodeScanerViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"扫一扫";
    self.navigationController.navigationBar.hidden = NO;
    self.tabBarController.tabBar.hidden = YES;
    
    [self beginScaning];
    
    [self initializeUserInterface];
}

#pragma mark - initialize
/**< 初始化用户界面 */
- (void)initializeUserInterface {
    // 扫描视图（同一个View实现中部镂空）
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(self.view.center.x - Size_W(150) - 500, self.view.center.y - Size_W(150) - 500, Size_W(300) + 1000, Size_W(300) + 1000)];
    view.backgroundColor = [UIColor clearColor];
    
    view.layer.borderWidth = 500;
    view.layer.borderColor = [UIColor colorWithWhite:0.0 alpha:0.5].CGColor;
    
    [self.view addSubview:view];
    
    // 上下移动的横线
    UIImageView *line = [[UIImageView alloc] init];
    line.bounds = CGRectMake(0, 0, Size_W(280), Size_H(5));
    line.center = CGPointMake(self.view.center.x, Size_H(240));
    line.image = IMAGE(@"二维码扫描横线");
    [self.view addSubview:line];

    // 1.创建动画对象
    CABasicAnimation *anim = [CABasicAnimation animation];
    // 2.设置动画属性
    anim.keyPath = @"position";
    anim.fromValue = [NSValue valueWithCGPoint:CGPointMake(self.view.center.x, Size_H(240))];
    anim.toValue = [NSValue valueWithCGPoint:CGPointMake(self.view.center.x, Size_H(510))];
    anim.duration = 4.0f;
    anim.repeatCount = HUGE_VALF;
    [line.layer addAnimation:anim forKey:nil];
}


#pragma mark - 开始扫描
- (void)beginScaning {
#pragma mark --获取输入设备（摄像头）
    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
    // 创建输入流
    AVCaptureDeviceInput *input = [AVCaptureDeviceInput deviceInputWithDevice:device error:nil];
    // 判断输入流是否存在
    if (!input) {
        return;
    }
    
#pragma mark --创建输出流
    AVCaptureMetadataOutput *output = [[AVCaptureMetadataOutput alloc] init];
    // 设置代理
    [output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()]; // 获取主队列（一个系统提供的串行队列）
    
    // 设置有效的扫描范围
    __weak typeof(self) weakSelf = self;
    [[NSNotificationCenter defaultCenter] addObserverForName:AVCaptureInputPortFormatDescriptionDidChangeNotification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification * _Nonnull note) {
        AVCaptureMetadataOutput *output = weakSelf.session.outputs.firstObject;
        // 设置应该扫描的区域
        //    CGRectMake (y的起点/屏幕的高, x的起点/屏幕的宽, 扫描区域的高/屏幕的高, 扫描区域的宽/屏幕的宽)
        output.rectOfInterest = CGRectMake((self.view.center.y - Size_W(150))/ScreenH, (self.view.center.x - Size_W(150))/ScreenW, Size_W(300)/ScreenH, Size_W(300)/ScreenW);
    }];
    
#pragma mark --初始化会话/链接
    self.session = [[AVCaptureSession alloc] init];
    // 高质量的采集率（可以不设置）
    self.session.sessionPreset = AVCaptureSessionPresetHigh;
    
    // 添加输入输出（异常处理）
    if ([self.session canAddInput:input]) {
        [self.session addInput:input];
    }
    if ([self.session canAddOutput:output]) {
        [self.session addOutput:output];
    }
    
    // 设置扫码支持的编码格式
    /*
     AVMetadataObjectTypeQRCode：二维码
     AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode128Code：条形码
     */
    output.metadataObjectTypes = @[AVMetadataObjectTypeQRCode, AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode128Code];
    
#pragma mark --预览图层
    self.previewLayer = [AVCaptureVideoPreviewLayer layerWithSession:self.session];
    self.previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    self.previewLayer.frame = CGRectMake(self.view.center.x - Size_W(150) - 500, self.view.center.y - Size_W(150) - 500, Size_W(300) + 1000, Size_W(300) + 1000);
    [self.view.layer addSublayer:self.previewLayer];
    
    
    // 开始捕获
    [self.session startRunning];
}


#pragma mark - 停止扫描
- (void)stopScaning {
    [self.session stopRunning];
    self.session = nil;
}

#pragma mark - <AVCaptureMetadataOutputObjectsDelegate>
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection {
    // 异常判断：扫描的编码是否有效
    if (metadataObjects != nil && metadataObjects.count > 0) {
        AVMetadataMachineReadableCodeObject *object = metadataObjects.firstObject;
        NSString *result;
        // 判断扫码的编码格式
        // 二维码
        if ([[object type] isEqualToString:AVMetadataObjectTypeQRCode]) {
            result = object.stringValue;
            // 1、判断是否是网址，询问用户是否打开 ...
            // 2、打开网址
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:result]];
        }
        // 条形码
        else {
            NSLog(@"扫描到的是条形码");
        }
    }
}

@end
